package com.atguigu.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.eduservice.entity.EduSubject;
import com.atguigu.eduservice.entity.excel.ExcelSubjectData;
import com.atguigu.eduservice.service.EduSubjectService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author kabuda
 * @create 2023-05-02 8:46
 */
@Transactional(rollbackFor = Exception.class)
public class SubjectReadListener extends AnalysisEventListener<ExcelSubjectData> {
    //监听器没有注入ioc，不能自动注入，手动传值过来
    private EduSubjectService eduSubjectService;
    public SubjectReadListener(EduSubjectService eduSubjectService) {
        this.eduSubjectService=eduSubjectService;
    }

    @Override
    public void invoke(ExcelSubjectData excelSubjectData, AnalysisContext analysisContext) {
        String oneSubjectName = excelSubjectData.getOneSubjectName();
        String twoSubjectName = excelSubjectData.getTwoSubjectName();
        EduSubject eduSubject = existSubject(oneSubjectName, "0");
        if(eduSubject==null){
            eduSubject=new EduSubject();
            eduSubject.setTitle(oneSubjectName);
            eduSubject.setParentId("0");
            eduSubjectService.save(eduSubject);
        }
        //如果存在一级分类的时候则直接获取id，如果不存在会插入数据，mp会返回id到实体类，也可以直接获取
        String oneLevelId = eduSubject.getId();
        EduSubject two = existSubject(twoSubjectName, oneLevelId);
        if(two==null) {
            two = new EduSubject();
            two.setTitle(twoSubjectName);
            two.setParentId(oneLevelId);
            eduSubjectService.save(two);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }


    private EduSubject existSubject(String title,String pid){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title",title).eq("parent_id",pid);
        EduSubject eduSubject = eduSubjectService.getOne(wrapper);
        return eduSubject;
    }
}
